/*  
 *  Battery Widget - Simple Android Battery Widget
 *  This application is redistributed from 
 *  Copyright (C) 2011 Henrique Rocha <hmrocha@gmail.com>
 */
package org.androidappdev.batterywidget;


import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.BatteryManager;
import android.os.IBinder;
import android.util.Log;
import android.widget.ImageView;
import android.widget.RemoteViews;

/**
 * Service to monitor battery level and temperature changes.
 * 
 * @author Henrique Rocha
 */
public class BatteryService extends Service {
	private static final String TAG = "BatteryService";
	private BroadcastReceiver batteryReceiver;
	private Integer currentLevel = 0;
	private int currentLayout = BatteryAppWidgetProvider.currentLayout;
	private int previousStatus = -1;
	private long timeRemain = -1;
	private long batConsumPerLev =-1;
	private long timeRecStart = -1;
	private long timeRecStop = -1;
	private int levelRecStart = -1;
	private int levelRecStop = -1;
	public static String ACTION_WIDGET_CONFIGURE = "ConfigureWidget";

	@Override
	public void onStart(Intent intent, int startId) {
		if (this.batteryReceiver == null) {
			this.batteryReceiver = batteryLevelReceiver();
			registerReceiver(this.batteryReceiver, new IntentFilter(
					Intent.ACTION_BATTERY_CHANGED));
		}

		// Build the widget update.
		RemoteViews updateViews = buildUpdate(this);
		Log.d("character", "updateViews");
		// Push update for this widget to the home screen
		ComponentName batteryWidget = new ComponentName(this,
				BatteryAppWidgetProvider.class);
		AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
		appWidgetManager.updateAppWidget(batteryWidget, updateViews);
	}

	/**
	 * Battery level receiver
	 * 
	 * @return a BroadcastReceiver to handle ACTION_BATTERY_CHANGED
	 */
	private BroadcastReceiver batteryLevelReceiver() {
		return new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				boolean needsUpdate = false;
				String action = intent.getAction();

				// Change dots to blue if charging.
				int status = intent.getIntExtra("status", 0);
				Log.d(TAG, "status: " + status);

				if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
					int level = intent.getIntExtra("level", 0);
					Log.d(TAG, "Level: " + level);
					// Only update widget if level changed, other changes
					// like temperature don't matter.
					if (currentLevel != level) {
						currentLevel = level;						
						needsUpdate = true;
					}

					if (level == 100)
						currentLayout = R.layout.level100;
					if (level <= 80)
						currentLayout = R.layout.level80;
					if (level <= 60)
						currentLayout = R.layout.level60;
					if (level <= 40)
						currentLayout = R.layout.level40;
					if (level <= 20)
						currentLayout = R.layout.level20;
					if (level <= 10)
						currentLayout = R.layout.level10;
					if (level == 0)
						currentLayout = R.layout.main;
					if(status == BatteryManager.BATTERY_STATUS_CHARGING)
						currentLayout = R.layout.charging;
					
					//when battery level change record time 
					if(timeRecStart<0)
					{
						timeRecStart = System.currentTimeMillis()/1000;
						levelRecStart = level;
						batConsumPerLev =0;

					}
					else
					{
						timeRecStop = System.currentTimeMillis()/1000;
						levelRecStop = level;
						batConsumPerLev = Math.abs(timeRecStop-timeRecStart)/Math.abs(levelRecStop-levelRecStart);
					}
				}

				if (status == BatteryManager.BATTERY_STATUS_CHARGING
						&& previousStatus != BatteryManager.BATTERY_STATUS_CHARGING) {
					BatteryAppWidgetProvider.currentLayout = R.layout.charging;
					needsUpdate = true;
				} else {
					BatteryAppWidgetProvider.currentLayout = currentLayout;
					
					needsUpdate = true;
				}
					
	        
		        
				if (needsUpdate) {
					Intent statusChanged = new Intent(context,
							BatteryService.class);
					context.startService(statusChanged);
					Log.d("battery","update interface");
				}
			}
		};
	}

	/**
	 * Build a widget update to show the current battery level.
	 */
	private RemoteViews buildUpdate(Context context) {
		String mm = "";
		BatteryAppWidgetProvider.currentLayout = this.currentLayout;
		RemoteViews views = new RemoteViews(context.getPackageName(),
				BatteryAppWidgetProvider.currentLayout);

		
		 Log.d("battery","buildUpdate");
		views.setTextViewText(R.id.battery_level, this.currentLevel.toString()+" %");
		timeRemain = this.currentLevel * batConsumPerLev/60; //Convert from Sec to Min
		if((timeRemain%60)<10)
			mm = "0"+timeRemain%60;
		else
			mm =timeRemain%60+"";
		
		if(timeRecStop>=0 && timeRecStart>=0)
		{
			
		
			views.setTextViewText(R.id.time_remain, timeRemain/60+":"+mm);
		}
		else
			views.setTextViewText(R.id.time_remain, "Inaccurate");
		//views.setTextViewText(R.id.time_remain, timeRemain/60+":"+timeRemain%60);
		//set character
		//setup resource
		String character = BatteryWidgetConfigure.getCharacterPref(context);
		String strcharacter = "penguin";
		long currentTime = System.currentTimeMillis()/1000;
		Log.d("character",String.valueOf(currentTime%4));
		if(character.equalsIgnoreCase("penguin"))
		{
			if(currentTime%4==0)
				strcharacter=character+"1";
			else if(currentTime%4==1)
				strcharacter=character+"2";
			else if(currentTime%4==2)
				strcharacter=character+"3";
			else if(currentTime%4==3)
				strcharacter=character+"4";
			else
				strcharacter=character+"1";
		}
		else if(character.equalsIgnoreCase("white"))
		{
			if(currentTime%4==0)
				strcharacter=character+"1";
			else if(currentTime%4==1)
				strcharacter=character+"2";
			else if(currentTime%4==2)
				strcharacter=character+"3";
			else if(currentTime%4==3)
				strcharacter=character+"4";
			else
				strcharacter=character+"1";
		}
		else if (character.equalsIgnoreCase("black"))
		{
			if(currentTime%4==0)
				strcharacter=character+"1";
			else if(currentTime%4==1)
				strcharacter=character+"2";
			else if(currentTime%4==2)
				strcharacter=character+"3";
			else if(currentTime%4==3)
				strcharacter=character+"4";
			else
				strcharacter=character+"1";
		}
		else 
		{
			if(currentTime%4==0)
				strcharacter=character+"1";
			else if(currentTime%4==1)
				strcharacter=character+"2";
			else if(currentTime%4==2)
				strcharacter=character+"3";
			else if(currentTime%4==3)
				strcharacter=character+"4";
			else
				strcharacter=character+"1";
		}
		
		Log.d("character",strcharacter);
		Resources res = getResources();
		String mDrawableName = "@drawable/"+strcharacter;
		int resID = res.getIdentifier(mDrawableName, "drawable", context.getPackageName());
		
		//create ImageView
		ImageView charImage = new ImageView(context);
		charImage.findViewById(R.id.imageView1);
		views.setImageViewResource(R.id.imageView1, resID);

		
		Intent intentConfig = new Intent(context, BatteryWidgetConfigure.class);   
		intentConfig.setAction(ACTION_WIDGET_CONFIGURE);
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intentConfig, 0);
		//RemoteViews views = new RemoteViews(context.getPackageName(),
		//		BatteryAppWidgetProvider.currentLayout);
		//RemoteViews views = new RemoteViews(context.getPackageName(), currentLayout);            
		views.setOnClickPendingIntent(R.id.widget, pendingIntent);
		intentConfig.setAction(ACTION_WIDGET_CONFIGURE);
		ComponentName cn = new ComponentName(context,
				BatteryAppWidgetProvider.class);
		AppWidgetManager.getInstance(context).updateAppWidget(cn, views);

		return views;
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// We don't need to bind to this service
		return null;
	}

}
